{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import accuracy_score, classification_report\n",
    "from sklearn.model_selection import train_test_split\n",
    "from tensorflow.keras.datasets import mnist\n",
    "import time\n",
    "\n",
    "# 记录开始时间\n",
    "start_time = time.time()\n",
    "\n",
    "# 加载MNIST数据集\n",
    "print(\"正在加载MNIST数据集...\")\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "\n",
    "# 数据预处理\n",
    "print(\"正在进行数据预处理...\")\n",
    "# 重塑数据为二维数组 (样本数, 特征数)\n",
    "x_train = x_train.reshape(x_train.shape[0], -1) / 255.0\n",
    "x_test = x_test.reshape(x_test.shape[0], -1) / 255.0\n",
    "\n",
    "# 划分训练集和验证集\n",
    "x_train, x_val, y_train, y_val = train_test_split(\n",
    "    x_train, y_train, test_size=0.1, random_state=42\n",
    ")\n",
    "\n",
    "print(f\"训练集形状: {x_train.shape}, 验证集形状: {x_val.shape}, 测试集形状: {x_test.shape}\")\n",
    "\n",
    "# 初始化逻辑回归模型\n",
    "print(\"正在初始化逻辑回归模型...\")\n",
    "# 多分类问题使用'ovr'策略（一对多）\n",
    "lr_model = LogisticRegression(\n",
    "    solver='lbfgs',       # 优化器，适合多分类\n",
    "    multi_class='multinomial',  # 多分类策略\n",
    "    max_iter=1000,       # 最大迭代次数\n",
    "    random_state=42,     # 随机种子，保证结果可复现\n",
    "    verbose=1            # 输出训练过程\n",
    ")\n",
    "\n",
    "# 训练模型\n",
    "print(\"开始训练模型...\")\n",
    "train_start = time.time()\n",
    "lr_model.fit(x_train, y_train)\n",
    "train_time = time.time() - train_start\n",
    "print(f\"模型训练完成，耗时: {train_time:.2f}秒\")\n",
    "\n",
    "# 在验证集上评估\n",
    "print(\"正在验证集上评估模型...\")\n",
    "val_pred = lr_model.predict(x_val)\n",
    "val_acc = accuracy_score(y_val, val_pred)\n",
    "print(f\"验证集准确率: {val_acc:.4f}\")\n",
    "\n",
    "# 在测试集上评估\n",
    "print(\"正在测试集上评估模型...\")\n",
    "test_pred = lr_model.predict(x_test)\n",
    "test_acc = accuracy_score(y_test, test_pred)\n",
    "print(f\"测试集准确率: {test_acc:.4f}\")\n",
    "\n",
    "# 输出分类报告\n",
    "print(\"\\n分类报告:\")\n",
    "print(classification_report(y_test, test_pred))\n",
    "\n",
    "# 可视化一些预测结果\n",
    "def visualize_predictions():\n",
    "    plt.figure(figsize=(12, 6))\n",
    "    # 随机选择10个样本\n",
    "    indices = np.random.choice(len(x_test), 10, replace=False)\n",
    "\n",
    "    for i, idx in enumerate(indices):\n",
    "        plt.subplot(2, 5, i+1)\n",
    "        # 重塑回图像形状\n",
    "        img = x_test[idx].reshape(28, 28)\n",
    "        plt.imshow(img, cmap='gray')\n",
    "        true_label = y_test[idx]\n",
    "        pred_label = test_pred[idx]\n",
    "        plt.title(f\"真实: {true_label}\\n预测: {pred_label}\")\n",
    "        plt.axis('off')\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "# 可视化预测结果\n",
    "print(\"可视化部分预测结果...\")\n",
    "visualize_predictions()\n",
    "\n",
    "# 计算总耗时\n",
    "total_time = time.time() - start_time\n",
    "print(f\"\\n整个流程耗时: {total_time:.2f}秒\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
